// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import Axios from 'axios'
import api from './api/index'
import store from './store/index'
import config from './config'
import qs from 'qs'
// import { mapGetters } from 'vuex'

Vue.prototype.$api = api
Axios.defaults.baseURL = 'http://120.27.20.92'
Vue.prototype.$axios = Axios
Vue.prototype.$qs = qs
Vue.config.productionTip = false
Vue.use(ElementUI)
// Vue.use(querystring)
Vue.prototype.formatDate = function (date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()
  //  return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
  return year + '-' + (String(month).length > 1 ? month : '0' + month) + '-' +
    (String(day).length > 1 ? day : '0' + day) + ' ' + (String(hour).length > 1 ? hour : '0' + hour) + ':' + (String(minute).length > 1 ? minute : '0' + minute) + ':' + (String(second).length > 1 ? second : '0' + second)
}
Vue.prototype.myImage = function (item) {
  return Axios.defaults.baseURL + item.replace(/\\/g, '/')
}
Vue.prototype.open = function (message, type) {
  this.$message({
    message: message,
    type: type
  })
}

// 将一个数据组件成路由的形式，并返回
function createRouter (arr) {
  let subRoutes = []
  arr.forEach((a) => {
    if (a.permission.length > 0) {
      a.permission.forEach((item) => {
        if (config.componentList.get(item.permissionName) !== ('' || undefined)) {
          let menu = config.componentList.get(item.permissionName).split('/')
          subRoutes.push({
            path: '/' + menu[menu.length - 1],
            name: menu[menu.length - 1],
            meta: { requireAuth: true, menuName: [a.permissionName, item.permissionName] },
            component: resolve => require(['@/views' + config.componentList.get(item.permissionName)], resolve)
          })
        }
      })
    } else {
      if (config.componentList.get(a.permissionName) !== ('' || undefined)) {
        let menu = config.componentList.get(a.permissionName).split('/')
        subRoutes.push({
          path: '/' + menu[menu.length - 1],
          name: menu[menu.length - 1],
          meta: { requireAuth: true, menuName: [a.permissionName, a.permissionName] },
          component: resolve => require(['@/views' + config.componentList.get(a.permissionName)], resolve)
        })
      }
    }
  })
  return subRoutes
}

// 执行动态添加路由
function myAddRouter () {
  let subRoutes = [{
    path: '/user/login',
    component: resolve => require(['@/views/login'], resolve)
  }, {
    path: '/',
    component: resolve => require(['@/views/leftNav'], resolve)
  }, {
    path: '/manage',
    component: resolve => require(['@/views/leftNav'], resolve),
    children: [
      {
        path: '',
        component: resolve => require(['@/views/home'], resolve)
      }, {
        path: '/',
        component: resolve => require(['@/views/home'], resolve)
      }, {
        path: '/home',
        component: resolve => require(['@/views/home'], resolve)
      }]
  }]
  subRoutes[subRoutes.length - 1].children.push(...createRouter(store.getters.getMenuInfo))
  if (store.getters.getCompany.status === 1) {
    subRoutes[subRoutes.length - 1].children.push(...[{
      path: '/createOrder',
      component: resolve => require(['@/views/createOrder/createOrder'], resolve),
      meta: ['生成订单', '生成订单']
    }, {
      path: '/submitOrder',
      component: resolve => require(['@/views/createOrder/submitOrder'], resolve),
      meta: ['提交订单', '提交订单']
    }, {
      path: '/productDetails',
      component: resolve => require(['@/views/productDetails'], resolve),
      meta: ['商品详情', '商品详情']
    }])
  }
  router.options.routes = subRoutes
  router.options.routes.push(
    {
      path: '*',
      name: '404',
      component: resolve => require(['@/views/Page404'], resolve)
    })
  router.addRoutes(router.options.routes)
}
router.beforeEach(function (to, from, next) {
  if (to.path === api.login.login) {
    next()
  } else {
    if (store.getters.getToken !== '' && store.getters.getIsLogin) {
      store.dispatch('setNoRefresh') // 重新刷新设置为false
      myAddRouter()// 添加动态路由的方法
      next()
    } else {
      next({
        path: api.login.login
      })
    }
  }
})
// eslint-disable-next-line no-new
const vm = new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App)
})

// 拦截器
// 拦截Axios发起的所有请求，给请求添加token
Axios.interceptors.request.use(
  config => {
    if (store.getters.getToken) { // 判断是否存在token，如果存在的话，则每个http header都加上token
      // console.log("request"+store.getters.getToken);
      config.headers['Authorization'] = store.getters.getToken
    } else {
      router.push({ path: api.login.login })
      config.headers['Authorization'] = ''
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })
Axios.interceptors.response.use((config) => {
  // console.log('in response')
  if (config.data.token) {
    // console.log('response' + config.data.token)
    vm.$store.dispatch('setToken', config.data.token)
  }
  return config
})
